<template>
    <div class="">
        <van-sticky>
            <van-nav-bar :title="isEdit ? '编辑地址' : '新增地址'" left-text="返回" left-arrow @click-left="$router.go(-1)" />
        </van-sticky>


        <van-address-edit :area-list="areaList" :address-info="formData" show-delete show-set-default
            :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave" @delete="onDelete" />

    </div>
</template>
<script>
import Vue from 'vue';
import request from '../../utils/request'
import { NavBar } from 'vant';
import { Sticky } from 'vant';
import { Card } from 'vant';
import { Button } from 'vant';
import { AddressEdit } from 'vant';
import { areaList } from '@vant/area-data';


Vue.use(AddressEdit);
Vue.use(Button);
Vue.use(Card);
Vue.use(Sticky);
Vue.use(NavBar);

export default {
    data() {
        return {
            areaList: areaList,
            isEdit: false,
            formData: {}
        }
    },
    created() {
        this.edited();
    },
    methods: {
        edited() {
            const addressId = this.$route.query.id;
            this.isEdit = !!addressId;
            if (this.isEdit) {
                this.addrDetail(addressId)
            }
        },
        async addrDetail(id) {
            let params = {
                addressId: id
            }
            await request.get('/address/detail', { params }).then(res => {
                console.log(res.result);
                this.formData = {
                    name: res.result.name,
                    tel: res.result.tel,
                    province: res.result.province,
                    city: res.result.city,
                    county: res.result.county,
                    addressDetail: res.result.addressDetail,
                    areaCode: res.result.areaCode,
                    postalCode: res.result.postalCode,
                    isDefault: res.result.isDefault
                };
            })
        },
        async onSave(content) {
            let url = this.isEdit ? `/address/edit?id=${this.$route.query.id}` : '/address/add';
            let data = {
                ...content,
                addressId: this.$route.query.id,
                province: content.province,
                city: content.city,
                county: content.county,
                areaCode: content.areaCode,
                isDefault: content.isDefault || false
            }
            await request.post(url,data);
            this.$router.go(-1);
        },
        async onDelete() {
            let data = {
                addressId: this.$route.query.id
            }
            await request.post('/address/del', data);
            this.$router.go(-1);
        },

    }
};
</script>

<style scoped></style>